import React, { Component } from "react";
import L from "leaflet";
import tileLayer from "./control/layer-canvas/L.tileLayer.canvas";
import {LeafletDrawLonlatLine} from "leaflet-lonlat-gridlines";
import "./mapview.css";

export default class MapView extends Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    this.initMap();
  }
  componentWillUnmount() {
    /**释放资源,移除经纬线相关图层和地图事件*/
    this.lonLatGridLines.removeDrawEvent();
  }

  initMap() {
    console.log(L);
    let option = {
      /**使用官方自带的默认的zoom组件*/
      zoomControl: true,
      /**是否将 attribution 版权控件添加到地图中，这里设置false*/
      attributionControl: false,
      /** 将地图视图限制在给定的范围内 */
      maxBounds: L.latLngBounds(L.latLng(-85.06, -180), L.latLng(85.06, 180)),
      /** 最大缩放层级 */
      maxZoom: 18,
      /** 最小缩放层级（一般3级就行了，再多显示效果就不好了！） */
      minZoom: 3,
    };
    let map = L.map("map", option);
    map.setView([33, 112], 12);
    let arcgis =
      "https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}";
    tileLayer(arcgis, { maxZoom: 18 }).addTo(map);
    this.lonLatGridLines = new LeafletDrawLonlatLine(map);
    /**经纬线设置为红色*/
    this.lonLatGridLines.setLineColor("red");
    /**经纬线度数文本颜色调整为黄色*/
    this.lonLatGridLines.setTextColor("yellow");
    /**经纬线度数文本四个方位（东西南北）均显示*/
    this.lonLatGridLines.setTextPosition("all");
  }

  doShowGrid(showGrid) {
    if (!this.lonLatGridLines) {
      return;
    }
    if (showGrid) {
      /** 添加绘制地图事件（即拖动地图时，清除上一次的图层的同时绘制新的图层）*/
      this.lonLatGridLines.addDrawEvent();
      /** 初始化话的时候，触发一次绘制*/
      this.lonLatGridLines.drawLonlatTileGrid();
    } else {
      this.lonLatGridLines.removeDrawEvent();
    }
  }

  render() {
    let { showGrid } = this.props;
    this.doShowGrid(showGrid);
    return <div id="map" className="container"></div>;
  }
}
